package cn.legend.travel.ask.controller;

import cn.legend.travel.ask.pojo.param.AddNewAnswerParam;
import cn.legend.travel.ask.service.AnswerService;
import cn.legend.travel.common.pojo.authentication.CurrentPrincipal;
import cn.legend.travel.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Pattern;

@RestController
@RequestMapping("answer")
@Api(tags = "回答模块")
public class AnswerController {
    @Autowired
    private AnswerService answerService;
    @ApiOperation("得到该问题最热门的回答")
    @GetMapping("getBestAsks")
    public JsonResult getBestAsk(@RequestParam Long questionId){
        return JsonResult.ok(answerService.getBestAsk(questionId));

    }
    @ApiOperation("添加回答")
    @PostMapping("addNewAnswer")
    public JsonResult addNewAnswer(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal,
                                   @RequestBody AddNewAnswerParam addNewAnswerParam){
        answerService.addNewAnswer(currentPrincipal,addNewAnswerParam);
        return JsonResult.ok();
    }
    @ApiOperation("添加点赞数量")
    @PostMapping("like")
    public JsonResult like(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal,
                           @RequestParam Long answerId){
        answerService.addLikes(answerId,currentPrincipal);
        return JsonResult.ok();
    }
    @ApiOperation("取消点赞")
    @PostMapping("cancelLike")
    public JsonResult cancelLike(@AuthenticationPrincipal @ApiIgnore CurrentPrincipal currentPrincipal,
                                 @RequestParam  Long answerId){
        answerService.cancelLikes(answerId,currentPrincipal);
        return JsonResult.ok();
    }
    @ApiOperation("推荐功能")
    @PostMapping("recommendation")
    public JsonResult view(@RequestParam Long answerId){
        answerService.AddViews(answerId);
        return JsonResult.ok();
    }
    @ApiOperation("搜索功能")
    @PostMapping("search")
    public JsonResult search(@RequestParam @Pattern(regexp = "^(?! )\\S{1,20}(?<! )$", message = "关键词必须是1~20个字符，且首尾不可以是空格！") String keyword,
                             @Range(min = 1, message = "请提交有效的页码值！") Integer page){
        return JsonResult.ok(answerService.search(keyword,page));
    }
    @ApiOperation("举报功能")
    @PostMapping("report")
    public JsonResult report(@RequestParam Long answerId){
        answerService.report(answerId);
        return JsonResult.ok();
    }
}
